package com.yu.common.handler;

import cn.hutool.db.meta.JdbcType;
import lombok.extern.java.Log;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

//@MappedJdbcTypes(JdbcType.VARCHAR) //数据库类型
@MappedTypes(List.class)
@Log
public class ListTypeHandler implements TypeHandler<List<String>>{

    @Override
    public void setParameter(PreparedStatement statement, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
        log.info("method ====>setParameter");
        String bodys =  dealListToOneStr(parameter);
        statement.setString(i, bodys);
    }

    private String dealListToOneStr(List<String> parmeter){
        if (parmeter ==null ||parmeter.size()<=0){
            return null;
        }
        String res = "";
        for (int i = 0; i < parmeter.size(); i++) {
            if (i==parmeter.size()-1){
                res += parmeter.get(i);
                return res;
            }
            res+=parmeter.get(i)+",";
        }
        return null;
    }

    @Override
    public List<String> getResult(ResultSet resultSet, String columenName) throws SQLException {
        return Arrays.asList(resultSet.getString(columenName).split(","));
    }

    @Override
    public List<String> getResult(ResultSet resultSet, int columnIndec) throws SQLException {
        return Arrays.asList(resultSet.getString(columnIndec).split(","));
    }

    @Override
    public List<String> getResult(CallableStatement callableStatement, int columnIndec) throws SQLException {
        return Arrays.asList(callableStatement.getString(columnIndec).split(","));
    }
}
